#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include "parse_url.h"
#define SERVER_ROOT "/home/sagi/projects/tinyserver"

void tinybuf_init (TinyBuff *tb, int fd)
{
	bzero(tb, sizeof(TinyBuff));
	tb->pos = tb->buf;
	tb->size = 0;
	tb->fd = fd;
}

int read_from_fd (TinyBuff *tb)
{
	int readn = 0, maxn = sizeof(tb->buf);

	while ((readn = read(tb->fd, tb->buf, maxn)) < 0) {
		if (errno == EINTR)
			continue;
		else
			return -1;
	}
	
	tb->size = readn;
	tb->pos = tb->buf;

	return tb->size;
}

char *read_line_from_buf (TinyBuff *tb, char *line)
{
	char *p = line;

	do {
		if (tb->size == 0) {
			if (read_from_fd(tb) == -1)
				return NULL;
			continue;
		}

		*p++ = *tb->pos++;
		tb->size--;
	} while (*tb->pos != '\n');

	*p++ = *tb->pos++;	/* *p == \n */
	*p++ = '\0';
	tb->size--;

	return line;
}

int parse_url (char *line, Url *url, Setting *setting)
{
	char *str;
#ifdef DEBUG
	printf("Server read line: %s", line);
#endif
	if ((str = strtok(line, " ")) != NULL) {
		if (!strncmp(str, "GET", 4)) {
			url->method = HTTP_GET;
		} else {
			url->method = HTTP_POST;
		}
#ifdef DEBUG
		printf("method:%d\n", url->method);
#endif
	} else {
		return -1;
	}


	if ((str = strtok(NULL, " ")) != NULL) {
		strncpy(url->uri, setting->st_root, sizeof(url->uri));
		strncat(url->uri, str, sizeof(url->uri));
#ifdef DEBUG
		printf("uri:%s\n", url->uri);
#endif
	} else {
		return -1;
	}

	if ((str = strtok(NULL, " ")) != NULL) {
		strncpy(url->protocol, str, sizeof(url->uri));
#ifdef DEBUG
		printf("protocol:%s\n", url->protocol);
#endif
	} else {
		return -1;
	}
	
	return 0;
}
/*
int main ()
{
	TinyBuff tb;
	Url url;
	char line[1024];

	tinybuf_init(&tb, STDIN_FILENO);
	//parse_url(&tb, &url);
	while (strncmp(read_line_from_buf(&tb, line), "\r\n")) {
		printf("line read: %s", line);
	}


	return 0;
}*/
